package cn.iocoder.yudao.module.system.util.a_gaojian;


import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;

/**
 * @author lxj
 * 音频
 */
public class AudioUtils {
    public static final String AUDIO_MP3 = "audio/mpeg";
    public static final String AUDIO_M4A = "audio/mp4";
    public static final String AUDIO_WMA = "audio/x-ms-wma";
    public static final String AUDIO_WAV = "audio/wave";
    public static final String AUDIO_AMR = "application/octet-stream";

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            "mp3", "m4a", "wma", "wav", "amr"
    };
    /**
     * 音频文件名最大长度
     */
    public static final int AUDIO_FILE_NAME_LENGTH_MAX = 80;
    /**
     * 音频文件大小最大限制 1MB
     */
    public static final long AUDIO_FILE_SIZE_MAX = 1 * 1024 * 1024;


    /**
     * 音频上传
     *
     * @param baseDir   相对应用的基目录
     * @param imageFile 音频文件
     * @return 音频文件名称
     */
    public static String upload(String baseDir, MultipartFile imageFile) throws IOException {
        return upload(baseDir, imageFile, DEFAULT_ALLOWED_EXTENSION);
    }

    /**
     * 音频上传
     *
     * @param baseDir       相对应用的基目录
     * @param bufferedImage 音频
     * @return 音频文件名称
     */
    public static String upload(String baseDir, BufferedImage bufferedImage) throws IOException {
        String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        File desc = getAbsoluteFile(baseDir, imageFileName);
        ImageIO.write(bufferedImage, "jpg", desc);
        String pathFileName = getPathFileName(imageFileName);
        return pathFileName;
    }

    /**
     * 音频上传
     *
     * @param baseDir          相对应用的基目录
     * @param imageFile        音频文件
     * @param allowedExtension 允许上传音频文件类型
     * @return 音频文件名称
     */
    public static String upload(String baseDir, MultipartFile imageFile, String[] allowedExtension) throws IOException {
        //int imageFileNameLength = imageFile.getOriginalFilename().length();
        //if (imageFileNameLength > AUDIO_FILE_NAME_LENGTH_MAX) {
        //throw new ServiceException(ApiResponseCodeEnum.FAIL, "音频文件名过长，最大长度为80字符");
        //error(200, "音频文件名过长，最大长度为80字符");
        //}

        //long size = imageFile.getSize();
        //if (AUDIO_FILE_SIZE_MAX > 0 && size > AUDIO_FILE_SIZE_MAX) {
        //  throw new ServiceException(ApiResponseCodeEnum.FAIL, "音频文件过大，最大限制为1MB");
        //error(200, "音频文件过大，最大限制为1MB");
        //}

        // 校验
        if (!assertAllowed(imageFile, allowedExtension)) {
            error(200, "音频文件格式错误，允许上传mp3,m4a,wma,wav,amr格式");
        }
        String imageFileName = extractFilename(imageFile);

        //原本逻辑---直接上传
        //File desc = getAbsoluteFile(baseDir, imageFileName);
        //imageFile.transferTo(desc);

        //切片上传
        FileUtils.splitFile(baseDir,imageFile,imageFileName);
        String pathFileName = getPathFileName(imageFileName);

        return pathFileName;
    }

    /**
     * 校验
     *
     * @param imageFile        音频文件
     * @param allowedExtension 允许上传音频文件类型
     */
    public static Boolean assertAllowed(MultipartFile imageFile, String[] allowedExtension) {
        String extension = getExtension(imageFile);
        //  throw new ServiceException(ApiResponseCodeEnum.FAIL, "音频文件格式错误，允许上传jpg,jpeg,png,gif,bmp格式");
        return isAllowedExtension(extension, allowedExtension);
    }

    /**
     * 获取音频文件名称的后缀
     *
     * @param imageFile 音频文件
     * @return 后缀
     */
    public static String getExtension(MultipartFile imageFile) {
        String extension = FilenameUtils.getExtension(imageFile.getOriginalFilename());
        if (StringUtils.isBlank(extension)) {
            extension = getExtension(imageFile.getContentType());
        }
        return extension;
    }

    public static String getExtension(String prefix) {
        switch (prefix) {
            case AUDIO_MP3:
                return "mp3";
            case AUDIO_M4A:
                return "m4a";
            case AUDIO_WMA:
                return "wma";
            case AUDIO_WAV:
                return "wav";
            case AUDIO_AMR:
                return "amr";
            default:
                return "";
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension        上传音频文件类型
     * @param allowedExtension 允许上传音频文件类型
     * @return true/false
     */
    public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile imageFile) {
        String extension = getExtension(imageFile);
        //String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
        String imageFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
        return imageFileName;
    }

    public static File getAbsoluteFile(String uploadDir, String imageFileName) {
        File desc = new File(uploadDir + File.separator + imageFileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static String getPathFileName(String imageFileName) {
        String pathFileName = "/" + imageFileName;
        return pathFileName;
    }


}
